package io.cloud.tec.project.web;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("process")
public class JdkProcessController {

    @GetMapping("cmd")
    public void cmd(HttpServletResponse response) {
        ProcessBuilder pb = new ProcessBuilder("/bin/zsh", "-c", "ping -c 10 www.baidu.com");
        Process process = null;
        try {
            File file = new File("ProcessBuilder.log");
            pb.redirectOutput(file);
            process = pb.start();
            process.waitFor();
            process.destroy();
            IOUtils.copy(new FileReader(file), response.getOutputStream(), StandardCharsets.UTF_8);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            try {
                response.getWriter().write("error");
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    @GetMapping("view")
    @ResponseBody
    public void view(HttpServletResponse response) {
        try {
            RandomAccessFile randomAccessFile = new RandomAccessFile("ProcessBuilder.log", "r");
            while (true) {
                String line = randomAccessFile.readLine();
//                randomAccessFile.seek();
                log.info("read from file: {}", line);
                response.getWriter().write(line);
                response.getWriter().write(System.lineSeparator());
                response.getWriter().flush();
                response.flushBuffer();
                TimeUnit.SECONDS.sleep(1);
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
